package com.ask.entity;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTCase1 {

    private static final String SECRET_KEY = "yourSecretKey";
    public static String generateToken(String subject){
        return Jwts.builder()
                .setSubject(subject)
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256" )
                // payload
                .claim("name", "Joe")
                .claim("role", "admin")
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
                // signature
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 验证JWT
    public static Claims validateToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }


    public static void main(String[] args) {
        String jwt = generateToken("user123");
        System.out.println("Generated JWT: " + jwt);

        Claims claims = validateToken(jwt);
        System.out.println("Subject: " + claims.getSubject());
        System.out.println("Expiration: " + claims.getExpiration());
    }
}
